package com.dormitory.ui;

import com.dormitory.model.Building;
import com.dormitory.model.Room;
import com.dormitory.service.BuildingService;
import com.dormitory.service.RoomService;
import com.dormitory.service.impl.BuildingServiceImpl;
import com.dormitory.service.impl.RoomServiceImpl;

import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public class RoomPanel extends JPanel {
    private RoomService roomService;
    private BuildingService buildingService;
    private JTable roomTable;
    private DefaultTableModel tableModel;
    private JTextField searchField;
    private JComboBox<Building> buildingComboBox;
    private JTextField roomNumberField;
    private JTextField capacityField;
    private JTextField occupancyField;
    private JComboBox<String> statusComboBox;
    private JPanel resultStatsPanel;

    public RoomPanel() {
        roomService = new RoomServiceImpl();
        buildingService = new BuildingServiceImpl();
        initUI();
        loadRoomData();
    }

    private void initUI() {
        setLayout(new BorderLayout());
        // 工具栏
        JToolBar toolBar = createToolBar();
        add(toolBar, BorderLayout.NORTH);
        
        // 创建结果统计面板
        resultStatsPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
        resultStatsPanel.setBorder(BorderFactory.createTitledBorder("搜索结果统计"));
        add(resultStatsPanel, BorderLayout.SOUTH);
        
        // 表格
        createTable();
        JScrollPane scrollPane = new JScrollPane(roomTable);
        add(scrollPane, BorderLayout.CENTER);
    }

    private JToolBar createToolBar() {
        JToolBar toolBar = new JToolBar();
        toolBar.setFloatable(false);

        // 搜索框
        searchField = new JTextField(20);
        JButton searchButton = new JButton("搜索");
        searchButton.addActionListener(e -> searchRooms());

        // 添加按钮
        JButton addButton = new JButton("添加");
        addButton.addActionListener(e -> showAddDialog());

        // 修改按钮
        JButton editButton = new JButton("修改");
        editButton.addActionListener(e -> showEditDialog());

        // 删除按钮
        JButton deleteButton = new JButton("删除");
        deleteButton.addActionListener(e -> deleteRoom());

        toolBar.add(new JLabel("搜索："));
        toolBar.add(searchField);
        toolBar.add(searchButton);
        toolBar.addSeparator();
        toolBar.add(addButton);
        toolBar.add(editButton);
        toolBar.add(deleteButton);

        return toolBar;
    }

    private void createTable() {
        String[] columnNames = {"房间编号", "所属楼栋", "房间号", "容量", "当前人数", "状态"};
        tableModel = new DefaultTableModel(columnNames, 0) {
            @Override
            public boolean isCellEditable(int row, int column) {
                return false;
            }
        };
        roomTable = new JTable(tableModel);
        roomTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    }

    private void loadBuildings() {
        buildingComboBox.removeAllItems();
        List<Building> buildings = buildingService.getAllBuildings();
        for (Building building : buildings) {
            buildingComboBox.addItem(building);
        }
    }

    private void loadRoomData() {
        tableModel.setRowCount(0);
        List<Room> rooms = roomService.getAllRooms();
        for (Room room : rooms) {
            addRoomToTable(room);
        }
        // 显示全部数据的统计信息
        updateSearchStats(rooms, "");
    }

    private void addRoomToTable(Room room) {
        Building building = buildingService.getBuildingById(room.getBuildingId());
        String buildingName = building != null ? building.getBuildingName() : "未知";
        
        Object[] rowData = {
            room.getRoomId(),
            buildingName,
            room.getRoomNumber(),
            room.getCapacity(),
            room.getCurrentOccupancy(),
            room.getRoomStatus()
        };
        tableModel.addRow(rowData);
    }

    private void searchRooms() {
        String condition = searchField.getText().trim();
        tableModel.setRowCount(0);
        List<Room> rooms = roomService.searchRooms(condition);
        
        // 更新表格数据
        for (Room room : rooms) {
            addRoomToTable(room);
        }
        
        // 更新统计信息
        updateSearchStats(rooms, condition);
    }

    private void updateSearchStats(List<Room> rooms, String searchCondition) {
        resultStatsPanel.removeAll();
        
        // 创建统计信息标签
        JLabel totalLabel = new JLabel(String.format("总房间数: %d", rooms.size()));
        JLabel searchLabel = new JLabel(String.format("搜索条件: %s", searchCondition.isEmpty() ? "全部" : searchCondition));
        
        // 按房间状态统计
        Map<String, Long> statusStats = rooms.stream()
            .collect(Collectors.groupingBy(Room::getRoomStatus, Collectors.counting()));
        JLabel statusLabel = new JLabel("房间状态分布: " + 
            statusStats.entrySet().stream()
                .map(e -> String.format("%s(%d间)", e.getKey(), e.getValue()))
                .collect(Collectors.joining(", ")));
        
        // 计算入住率
        long occupiedRooms = rooms.stream()
            .filter(room -> room.getCurrentOccupancy() > 0)
            .count();
        double occupancyRate = rooms.isEmpty() ? 0 : (double) occupiedRooms / rooms.size() * 100;
        JLabel occupancyLabel = new JLabel(String.format("入住率: %.1f%%", occupancyRate));
        
        // 添加统计信息到面板
        resultStatsPanel.add(totalLabel);
        resultStatsPanel.add(new JLabel(" | "));
        resultStatsPanel.add(searchLabel);
        resultStatsPanel.add(new JLabel(" | "));
        resultStatsPanel.add(statusLabel);
        resultStatsPanel.add(new JLabel(" | "));
        resultStatsPanel.add(occupancyLabel);
        
        // 刷新面板
        resultStatsPanel.revalidate();
        resultStatsPanel.repaint();
    }

    private void showAddDialog() {
        RoomFormDialog dialog = new RoomFormDialog(SwingUtilities.getWindowAncestor(this), null);
        dialog.setVisible(true);
        if (dialog.isConfirmed()) {
            Room room = dialog.getRoom();
            if (roomService.addRoom(room)) {
                JOptionPane.showMessageDialog(this, "添加成功！");
                loadRoomData();
            } else {
                JOptionPane.showMessageDialog(this, "添加失败！");
            }
        }
    }

    private void showEditDialog() {
        int selectedRow = roomTable.getSelectedRow();
        if (selectedRow == -1) {
            JOptionPane.showMessageDialog(this, "请先选择要修改的房间！");
            return;
        }
        Integer roomId = (Integer) tableModel.getValueAt(selectedRow, 0);
        Room room = roomService.getRoomById(roomId);
        if (room == null) {
            JOptionPane.showMessageDialog(this, "未找到房间信息！");
            return;
        }
        RoomFormDialog dialog = new RoomFormDialog(SwingUtilities.getWindowAncestor(this), room);
        dialog.setVisible(true);
        if (dialog.isConfirmed()) {
            Room updated = dialog.getRoom();
            updated.setRoomId(roomId);
            if (roomService.updateRoom(updated)) {
                JOptionPane.showMessageDialog(this, "修改成功！");
                loadRoomData();
            } else {
                JOptionPane.showMessageDialog(this, "修改失败！");
            }
        }
    }

    private void deleteRoom() {
        int selectedRow = roomTable.getSelectedRow();
        if (selectedRow == -1) {
            JOptionPane.showMessageDialog(this, "请先选择要删除的房间！");
            return;
        }

        int confirm = JOptionPane.showConfirmDialog(this,
            "确定要删除这个房间吗？", "确认删除",
            JOptionPane.YES_NO_OPTION);
        
        if (confirm == JOptionPane.YES_OPTION) {
            Integer roomId = (Integer) tableModel.getValueAt(selectedRow, 0);
            if (roomService.deleteRoom(roomId)) {
                JOptionPane.showMessageDialog(this, "删除成功！");
                loadRoomData();
            } else {
                JOptionPane.showMessageDialog(this, "删除失败！");
            }
        }
    }
} 